import React, {
    forwardRef,
    useEffect,
    useImperativeHandle,
    useState,
    useCallback
} from 'react';
import { Form, Row, Col } from 'antd';
import { componentMap } from '@/components/SlForm/componentMap';
import { setFormIsShow, getComponentProps } from '@/components/SlForm/helper';
import type { ColProps } from 'antd';
import type {
    DynamicFormProps,
    FormItemConfig,
    FormSetPropsType,
} from '@/types/form';
import { set } from 'lodash-es';
import FormRules from "@/components/SlForm/FormRules.ts";

const SlForm = forwardRef(
    (
        {
            schema,
            formId = 'formRef',
            layout,
            handlers,
            // 改为 value 和 onChange 实现双向绑定
            formList: formValue = {},
            onChange,
            slots,
            isCol = true,
            gutter = 10,
        }: DynamicFormProps,
        ref,
    ) => {
        const [form] = Form.useForm();
        const [formValues, setFormValues] = useState<Record<string, any>>(formValue);
        const [initialSchema, setInitialSchema] = useState<FormItemConfig[]>([]);

        // 监听外部传入的 value 变化
        useEffect(() => {
            if (formValue && JSON.stringify(formValue) !== JSON.stringify(formValues)) {
                setFormValues(formValue);
                form.setFieldsValue(formValue);
            }
        }, [formValue]);

        // 处理表单值变化
        const handleValuesChange = useCallback((changedValues: any, allValues: any) => {
            console.log(changedValues, allValues, '----------')
            // 更新内部状态
            setFormValues(allValues);

            // 触发外部 onChange 事件
            if (onChange) {
                onChange(allValues);
            }

            // 如果有自定义的 onValuesChange 处理函数
            if (handlers?.onValuesChange) {
                handlers.onValuesChange(changedValues, allValues);
            }
        }, [onChange, handlers]);

        useEffect(() => {
            setInitialSchema(schema);
        }, [schema]);

        const setSchema = (schemaProps: FormSetPropsType[]) => {
            for (const v of schema) {
                for (const item of schemaProps) {
                    if (v.field === item.field) {
                        set(v, item.path, item.value);
                    }
                }
            }
            setInitialSchema([...schema]); // 创建新数组触发重新渲染
        };

        // 将 form 实例暴露给父组件
        useImperativeHandle(ref, () => ({
            getFieldsValue: () => form.getFieldsValue(),
            setValue: (values: any) => {
                setFormValues(values);
                form.setFieldsValue(values);
                if (onChange) {
                    onChange(values);
                }
            },
            setFieldsValue: (fieldsValue: any) => {
                setFormValues(fieldsValue);
                form.setFieldsValue(fieldsValue);
                if (onChange) {
                    onChange(fieldsValue);
                }
            },
            resetFields: () => {
                form.resetFields();
                const emptyValues = {};
                setFormValues(emptyValues);
                if (onChange) {
                    onChange(emptyValues);
                }
            },
            setFields: (fieldsValue: any) => form.setFields(fieldsValue),
            validateFields: () => form.validateFields(),
            submit: () => form.submit(),
            setSchema: setSchema,
            getForm: () => form,
        }));

        const renderFormItem = (item: FormItemConfig) => {
            const Component = componentMap[item.component] as React.ElementType;
            if (!Component) return null;

            const componentProps = getComponentProps({
                item,
                form,
                initialValues: formValues,
                handlers,
                slots,
            });

            // 添加双向绑定支持
            const enhancedProps = {
                ...componentProps,
                value: formValues[item.field],
                onChange: (value: any) => {
                    const newValues = { ...formValues, [item.field]: value };
                    setFormValues(newValues);
                    form.setFieldsValue({ [item.field]: value });

                    if (onChange) {
                        onChange(newValues);
                    }

                    if (componentProps.onChange) {
                        componentProps.onChange(value);
                    }
                }
            };

            return (
                <Form.Item
                    key={item.field}
                    name={item.field}
                    label={item.label}
                    rules={item.rules}
                    {...(item.formItemProps || {})}
                >
                    <Component {...enhancedProps} />
                </Form.Item>
            );
        };

        const renderForm = () => {
            return initialSchema
                .filter((v: FormItemConfig) => setFormIsShow(v, formValues))
                .map((item: FormItemConfig) => {
                    const itemCopy = JSON.parse(JSON.stringify(item));
                    FormRules.createRules(itemCopy);
                    const colProps: ColProps = itemCopy.colProps
                        ? { ...itemCopy.colProps }
                        : {};
                    return isCol ? (
                        <Col key={`form-${itemCopy.field}`} {...colProps}>
                            {renderFormItem(itemCopy)}
                        </Col>
                    ) : (
                        renderFormItem(itemCopy)
                    );
                });
        };

        return (
            <Form
                form={form}
                layout={layout}
                id={formId}
                initialValues={formValue}
                onValuesChange={handleValuesChange}
                onFinish={(values) => handlers?.onFinish?.(values)}
            >
                {isCol ? (
                    <Row style={{ width: '100%' }} gutter={gutter}>
                        {renderForm()}
                    </Row>
                ) : (
                    renderForm()
                )}
            </Form>
        );
    },
);

export default SlForm;